package com.tarena.lbs.content.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.content.dao.mapper.CategoryMapper;
import com.tarena.lbs.content.dao.repository.CategoryRepository;
import com.tarena.lbs.content.pojo.param.ArticleCategoryParam;
import com.tarena.lbs.content.pojo.po.ArticleCategoryPO;
import com.tarena.lbs.content.pojo.query.ArticleCategoryQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public class CategoryRepositoryImpl implements CategoryRepository {
    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public PageInfo<ArticleCategoryPO> pagesList(ArticleCategoryQuery query) {
        QueryWrapper<ArticleCategoryPO> queryWrapper=assembleCategoryQuery(query);
        PageHelper.startPage(query.getPageNo(),query.getPageSize());
        List<ArticleCategoryPO> pos=categoryMapper.selectList(queryWrapper);
        return new PageInfo<>(pos);
    }

    @Override
    public Optional<ArticleCategoryPO> findById(Integer articleCategoryId) {
        return Optional.ofNullable(categoryMapper.selectById(articleCategoryId));
    }

    @Override
    public void addCategory(ArticleCategoryPO po) {
        categoryMapper.insert(po);
    }

    @Override
    public void deleteCategory(Integer id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public void updateCategory(ArticleCategoryParam param) {
        ArticleCategoryPO po = new ArticleCategoryPO();
        po.setId(param.getId());
        po.setCategoryName(param.getCategoryName());
        po.setCategoryStatus(param.getCategoryStatus());
        categoryMapper.updateById(po);
    }

    private QueryWrapper<ArticleCategoryPO> assembleCategoryQuery(ArticleCategoryQuery query) {
        QueryWrapper<ArticleCategoryPO> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(query.getCategoryName())) {
            queryWrapper.like("category_name", query.getCategoryName());
        }
        if (query.getCategoryStatus() != null) {
            queryWrapper.eq("category_status", query.getCategoryStatus());
        }
        return queryWrapper;
    }
}